/* eslint-disable eqeqeq */
import React from 'react';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Input, Select, Row, Col, Switch, Spin } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import ReactQuill from 'react-quill'; // 引入富文本编辑器
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import 'react-quill/dist/quill.snow.css';
import FooterToolbar from '@/components/FooterToolbar';
import DictCode from '../../components/DictCode';

const { Option } = Select;
const FormItem = Form.Item;

@connect(({ material, loading, templatesettings }) => ({
  material,
  templatesettings,
  loading: loading.models.material,
}))
@Form.create()
class AddNotify extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isOpenProSet: false,
      informContent: null,
      pdList: [
        {
          id: new Date().getTime(),
          pdIds: '',
          informContent: '',
        },
      ],
      listIndex: 1,
    };
  }

  componentDidMount = () => {
    const { dispatch, location, form } = this.props;
    dispatch({
      type: 'material/fetchAreaList',
      payload: {},
    });
    dispatch({
      type: 'material/fetchPdList',
      payload: {},
    });
    if (location.query.id) {
      dispatch({
        type: 'templatesettings/fetchNotifyDetail',
        payload: { entryInformId: location.query.id },
      }).then(values => {
        Object.keys(values).forEach(key => {
          if (key == 'asscList') {
            const pdList = values[key];
            form.setFieldsValue({
              switch: true,
            });
            this.setState(
              {
                isOpenProSet: true,
                pdList: values[key],
              },
              () => {
                const getFieldsList = form.getFieldsValue();
                pdList.forEach(item => {
                  Object.keys(getFieldsList).forEach(keys => {
                    if (keys === `msgContent_${item.entryInformAsscId}`) {
                      form.setFieldsValue({
                        [keys]: item.msgContent,
                      });
                    } else if (keys === `productId_${item.entryInformAsscId}`) {
                      const a1 = item.pdId.split(',');
                      const b1 = item.pdName.split(',');
                      const aa = [];
                      for (let i = 0; i < a1.length; i += 1) {
                        aa.push(`${a1[i]}-${b1[i]}`);
                        form.setFieldsValue({
                          [keys]: this.tojson(aa),
                        });
                      }
                    } else if (keys === `informContent_${item.entryInformAsscId}`) {
                      this.setState({
                        [`informContent_${item.entryInformAsscId}`]: item.informContent,
                      });
                      this.changeQuilFunc(item.id, item.entryInformAsscId, item.informContent);
                    }
                  });
                });
              }
            );
          } else if (key === 'areaId' || key === 'areaIdName') {
            const a1 = values.areaId.split(',');
            const b1 = values.areaIdName.split(',');
            const aa = [];
            for (let i = 0; i < a1.length; i += 1) {
              aa.push(`${a1[i]}-${b1[i]}`);
              form.setFieldsValue({
                areaIds: this.tojson(aa),
              });
            }
          } else if (key === 'contType' || key === 'contTypeName') {
            const a1 = values.contType.split(',');
            const b1 = values.contTypeName.split(',');
            const aa = [];
            for (let i = 0; i < a1.length; i += 1) {
              aa.push(`${a1[i]}-${b1[i]}`);
              form.setFieldsValue({
                contTypes: this.tojson(aa),
              });
            }
          } else if (key !== 'informContent' && key === 'remark') {
            form.setFieldsValue({
              [key]: values[key],
            });
          }
          if (key === 'informContent') {
            this.setState({ [key]: values[key] });
          }
        });
      });
    }
  };

  // json处理
  tojson = arr => {
    if (!arr.length) return null;
    const arrays = [];
    const newArr = [];
    for (let i = 0; i < arr.length; i += 1) {
      newArr.push(arr[i].split('-'));
      arrays.push({
        key: newArr[i][0],
        label: newArr[i][1],
      });
    }
    return arrays;
  };

  componentWillUnmount = () => {
    const { dispatch } = this.props;
    const parameter = {
      entryInformId: null,
      vno: null,
      parameter: {},
    };
    dispatch({
      type: 'templatesettings/updateModelData',
      payload: parameter,
    });
  };

  submitcancel = () => {
    router.goBack();
  };

  // 提交数据
  submitAll = e => {
    const { form, dispatch } = this.props;

    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { isOpenProSet, pdList } = this.state;
        const pdLists = pdList.map(item => ({ ...item }));
        dispatch({
          type: 'templatesettings/fetchNotifySave',
          payload: { isOpenProSet, pdLists, values },
        });
      }
    });
  };

  // 富文本处理
  changeQuil = value => {
    const { form } = this.props;
    const str = JSON.stringify(value);
    str.replace(/<[^>]+>/g, '');
    if (str.replace(/<[^>]+>/g, '') != '""') {
      this.setState({
        informContent: value,
      });
      form.setFieldsValue({ informContent: value });
    } else {
      this.setState({
        informContent: undefined,
      });
      form.setFieldsValue({ informContent: undefined });
    }
  };

  // index,id
  changeQuilFunc = (id, modifyId, value) => {
    const { form } = this.props;
    const { pdList } = this.state;
    const str = JSON.stringify(value);
    str.replace(/<[^>]+>/g, '');
    if (str.replace(/<[^>]+>/g, '') != '""') {
      if (id) {
        pdList.forEach(item => {
          const newItem = item;
          if (String(newItem.id) === String(id)) {
            newItem.informContent = value;
          }
        });
        form.setFieldsValue({ [`informContent_${id}`]: value });
      } else if (modifyId) {
        pdList.forEach(item => {
          const newItem = item;
          if (String(newItem.entryInformAsscId) === String(modifyId)) {
            newItem.informContent = value;
          }
        });
        form.setFieldsValue({ [`informContent_${modifyId}`]: value });
      }
    } else if (id) {
      pdList.forEach(item => {
        const newItem = item;
        if (String(newItem.id) === String(id)) {
          newItem.informContent = undefined;
        }
      });
      form.setFieldsValue({ [`informContent_${id}`]: undefined });
      this.setState({ [`informContent_${id}`]: undefined });
    } else if (modifyId) {
      pdList.forEach(item => {
        const newItem = item;
        if (String(newItem.entryInformAsscId) === String(modifyId)) {
          newItem.informContent = undefined;
        }
      });
      form.setFieldsValue({ [`informContent_${modifyId}`]: undefined });
      this.setState({ [`informContent_${modifyId}`]: undefined });
    }
  };

  linkRoute = (id, path) =>
    id
      ? router.push(`/careermanage/inmaterialmanage/${path}?id=${id}`)
      : router.push(`/careermanage/${path}`);

  // 特殊产品
  changeProSet = checked => {
    this.setState({ isOpenProSet: checked });
  };

  // 新增产品
  addPd = () => {
    const { pdList } = this.state;
    const newData = pdList.map(item => ({ ...item }));
    newData.push({
      id: new Date().getTime(),
      pdIds: '',
      informContent: '',
    });
    this.state.listIndex += 1;
    this.setState({ pdList: newData });
  };

  // 删除产品
  delList = index => {
    const { pdList } = this.state;
    const newData = pdList.filter(item => item.id !== index);
    this.setState({ pdList: newData });
  };

  render() {
    const { form, material, loading } = this.props;
    const { getFieldDecorator } = form;
    const { isOpenProSet, pdList, informContent } = this.state;
    const { areaList, pdListData } = material;
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 18,
        },
        sm: {
          span: 6,
        },
      },
      wrapperCol: {
        xs: {
          span: 18,
        },
        sm: {
          span: 18,
        },
      },
    };
    const formItemLayout1 = {
      labelCol: {
        xs: {
          span: 18,
        },
        sm: {
          span: 4,
        },
      },
      wrapperCol: {
        xs: {
          span: 18,
        },
        sm: {
          span: 18,
        },
      },
    };
    const nowModules = {
      toolbar: [
        [
          {
            header: [1, 2, 3, 4, 5, 6, false],
          },
        ], // 文字大小
        ['bold', 'italic', 'underline'], // 切换组，【加粗、倾斜、下划线、删除线strike】
        [
          {
            size: ['small', false, 'large', 'huge'],
          },
        ], // 行距
        [
          {
            color: [],
          },
          {
            background: [],
          },
        ], // 文字颜色，背景色
        [
          {
            font: [],
          },
        ], // font-family
        [
          {
            align: [],
          },
        ], // text-align
        ['clean'], // 清除所有样式
      ],
    };
    // 富文本编辑器总配置
    const quillConfig = {
      theme: 'snow',
      modules: nowModules,
      placeholder: '请输入邮件模版',
    };
    const pOption = pdListData.map(email => <Option key={email.pdId}>{email.pdName}</Option>);

    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading}>
          <Card title="添加入职告知">
            <Form>
              <Row>
                <Col span={8}>
                  <FormItem {...formItemLayout} label={<span>地区 </span>}>
                    {getFieldDecorator('areaIds', {
                      rules: [
                        {
                          required: true,
                          message: '请填写地区',
                        },
                      ],
                    })(
                      <Select
                        placeholder="请选择地区"
                        mode="multiple"
                        labelInValue
                        onSelect={this.onChangeArea}
                        allowClear
                        showSearch
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                      >
                        {areaList.map(item => (
                          <Option key={item.areaId}>{item.areaName}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem {...formItemLayout} label="合同类型:">
                    {getFieldDecorator('contTypes', {
                      rules: [
                        {
                          required: true,
                          message: '请选择合同类型',
                        },
                      ],
                    })(<DictCode dictType="SER_TYPE" labelInValue mode="multiple" />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem {...formItemLayout} label={<span>备注</span>}>
                    {getFieldDecorator('remark', {
                      rules: [
                        {
                          required: false,
                          message: '请填写字数不超过100字的备注',
                          max: 100,
                        },
                      ],
                    })(<Input placeholder="请填写字数不超过100字的备注" />)}
                  </FormItem>
                </Col>
              </Row>
              <p style={{ border: '1px dashed #ebebeb' }} />

              <Row>
                <Col span={22}>
                  <FormItem {...formItemLayout1} label={<span>入职告知</span>}>
                    {getFieldDecorator('informContent', {
                      rules: [
                        {
                          required: true,
                          message: '请填写入职告知',
                        },
                      ],
                    })(
                      <div>
                        <ReactQuill
                          {...quillConfig}
                          value={informContent}
                          onChange={this.changeQuil}
                          style={{ lineHeight: 0 }}
                        />
                      </div>
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={22} offset={2}>
                  注解：{'{ name }'}、{'{ company }'}。
                  设置模板时，在文本中增加上述大括号+编码，即可在实际使用时自动获取对应的值。 （
                  {'"{name}"'}=员工姓名，{'"{company}"'}=公司名称）
                </Col>
              </Row>
            </Form>
          </Card>
          <Card
            title={
              <div>
                <span
                  style={{
                    marginRight: 20,
                  }}
                >
                  特殊产品设置
                </span>
                {getFieldDecorator('switch', { valuePropName: 'checked' })(
                  <Switch
                    checkedChildren="开"
                    unCheckedChildren="关"
                    onChange={this.changeProSet}
                  />
                )}
              </div>
            }
          >
            {isOpenProSet ? (
              <div>
                {pdList.map(item => (
                  <div key={item.id}>
                    <Row>
                      <Col span={22}>
                        <FormItem {...formItemLayout1} label={<span>关联产品</span>}>
                          {getFieldDecorator(
                            item.entryInformAsscId
                              ? `productId_${item.entryInformAsscId}`
                              : `productId_${item.id}`,
                            {
                              rules: [
                                {
                                  required: true,
                                  message: '请选择产品',
                                },
                              ],
                            }
                          )(
                            <Select
                              mode="multiple"
                              style={{ width: '100%' }}
                              placeholder="请选择服务产品"
                              labelInValue
                              onChange={this.handleChange}
                              allowClear
                              showSearch
                              filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >=
                                0
                              }
                            >
                              {pOption}
                            </Select>
                          )}
                        </FormItem>
                      </Col>
                      {pdList.length > 1 ? (
                        <DeleteOutlined
                          className="dynamic-delete-button"
                          onClick={() => this.delList(item.id)}
                        />
                      ) : null}
                    </Row>
                    <Row>
                      <Col span={22}>
                        <FormItem {...formItemLayout1} label={<span>入职告知</span>}>
                          {getFieldDecorator(
                            item.entryInformAsscId
                              ? `informContent_${item.entryInformAsscId}`
                              : `informContent_${item.id}`,
                            {
                              rules: [
                                {
                                  required: true,
                                  message: '请填写入职告知',
                                },
                              ],
                            }
                          )(
                            <div>
                              <ReactQuill
                                {...quillConfig}
                                value={item.informContent}
                                onChange={value =>
                                  this.changeQuilFunc(item.id, item.entryInformAsscId, value)
                                }
                                style={{ lineHeight: 0 }}
                              />
                            </div>
                          )}
                        </FormItem>
                      </Col>
                    </Row>
                    {pdList.length > 1 ? (
                      <div
                        style={{
                          marginBottom: '16px',
                          borderBottom: '1px solid #e8e8e8',
                        }}
                      />
                    ) : (
                      ''
                    )}
                  </div>
                ))}

                <div style={{ textAlign: 'center' }}>
                  <Button
                    type="dashed"
                    style={{ width: '70%' }}
                    icon={<PlusOutlined />}
                    onClick={this.addPd}
                  >
                    添加
                  </Button>
                </div>
              </div>
            ) : null}
          </Card>
        </Spin>
        <FooterToolbar>
          <Button onClick={this.submitcancel}>取消</Button>
          <Button type="primary" onClick={this.submitAll}>
            保存
          </Button>
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}

export default AddNotify;
